import React from 'react'
import { connect } from 'react-redux'
import {messages} from "share/common";
import 'styles/finance-setting/auto-audit/auto-audit.scss'
import { Button, Popover, Checkbox, Spin } from 'antd'
import { message } from 'antd';
import SlideFrame from "components/slide-frame";
import ListSelector from 'components/list-selector'
import AutoAuditRule from "containers/finance-setting/auto-audit/auto-audit-rule"
import autoAuditService from 'containers/finance-setting/auto-audit/auto-audit.service'
import menuRoute from "routes/menuRoute";
import ResizeTable from 'components/resize-table'
const CheckboxGroup = Checkbox.Group;

class AutoAudit extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      columns: [
        {title: messages('finance-setting.key74'/*优先级*/), dataIndex: 'priority'},
        {title: messages('finance-setting.key71'/*规则编码*/), dataIndex: 'ruleCode'},
        {title: messages('finance-setting.key72'/*规则名称*/), dataIndex: 'ruleName', render: value => <Popover content={value}>{value}</Popover>},
        {title: messages('finance-setting.key73'/*所属帐套*/), dataIndex: 'setOfBooksName'},
        {
          title: messages('common.operation')/*操作*/, dataIndex: 'operate',
          render: (value,record) => {
            return (
              <span>
                <a onClick={(e) => this.editRule(e,record)} disabled={!this.props.tenantMode}>{messages('common.edit')/*编辑*/}</a>
                <a onClick={(e) => this.goDetail(e,record)} style={{marginLeft:'8px'}}>{messages('common.detail')/*详情*/}</a>
              </span>
            )
          }
        }
      ],
      rowSelection: {
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      pagination: {
        total: 0,
      },
      page: 0,
      size: 10,
      tableLoading: false,
      showAuditRule: false,
      title: '',
      data: [],
      ruleInfo: {},
      showCompanyAssign: false,
      selectedDataIds: [], //选中的规则id
      setOfBookId: '',
      editing: false,
      editInfo: {},
      copyInfo: {},
      loading: false,
      saveLoading: false
    }
  }

  componentWillMount(){
    this.getSetting();
    this.getList();
  };

  getSetting = () => {
    this.setState({loading: true});
    autoAuditService.getAutoSetting().then(res => {
      this.setState({
        editInfo: this.getValue(res.data),
        copyInfo: JSON.parse(JSON.stringify(this.getValue(res.data))),
        loading: false
      });
    }).catch(e => {
      this.setState({loading: false});
      message.error(e.response.data.message);
    })
  };

  getValue = data => {
    let res = {};
    res.enableAuto = data.enableAuto;
    res.enableManual = data.enableManual;
    return res;
  };

  getList = () => {
    this.setState({tableLoading:true});
    const { page, size, rowSelection } = this.state;
    rowSelection.selectedRowKeys = [];
    let params = {
      tenantId: this.props.tenantInfo.id,
      page: page,
      size: size
    };
    autoAuditService.getAutoAuditRule(params).then(res => {
      this.setState({
        data: res.data,
        tableLoading: false,
        selectedDataIds: [],
        rowSelection,
        pagination: {
          total: Number(res.headers['x-total-count']),
          onChange: this.onChangePager,
          current: page + 1
        }
      });
    }).catch(() => {
      message.error(messages('finance-setting.key79'/*出错了，请联系管理员*/));
    });
  };

  //分页
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  //选择项改变触发事件
  onSelectChange = (selectedRowKeys) => {
    const { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  //点击选择
  onSelectItem = (record, selected) => {
    let {selectedDataIds, rowSelection} = this.state;
    if(!selected){
      selectedDataIds.map((select, index) => {
        if( select.id === record.id ){
          selectedDataIds.splice(index, 1);
        }
      })
    } else {
      selectedDataIds.push(record);
    }
    this.setState({ selectedDataIds ,rowSelection:rowSelection});
  };

  //全选
  onSelectAll = (selected, selectedRows, changeRows) => {
    let {selectedDataIds} = this.state;
    if(!selected){
      changeRows.map(record => {
        selectedDataIds.map((select, index) => {
          if( select.id === record.id ){
            selectedDataIds.splice(index, 1);
          }
        })
      });
    } else {
      selectedRows.map(item => {
        let isContainer = false;
        selectedDataIds.map(select => {
          if( select.id === item.id ){
            isContainer = true;
          }
        });
        !isContainer && (selectedDataIds.push(item));
      });
    }
    this.setState({selectedDataIds});
  };

  //新建规则
  newAuditRule = () => {
    this.setState({
      title: messages('finance-setting.key84'/*新建规则*/),
      ruleInfo: {}
    },() => {
      this.setState({showAuditRule: true});
    })
  };

  //分配公司
  assignCompany = () => {
    const { selectedDataIds } = this.state;
    let isSame = true;
    if(selectedDataIds.length){
      selectedDataIds.map(item => {
        item.setOfBooksId !== selectedDataIds[0].setOfBooksId && (isSame = false);
      });
    }else{
      isSame = false;
    }
    if(isSame){
      this.setState({setOfBookId: selectedDataIds[0].setOfBooksId}, () => {
        this.setState({showCompanyAssign: true});
      });
    }else{
      selectedDataIds.length ? message.error(messages('finance-setting.key98'/*请选择帐套相同的规则进行公司分配*/)) : message.error(messages('finance-setting.key99'/*请至少选择一项规则进行公司分配*/));
    }
  };

  //编辑规则
  editRule = (e,record) => {
    e.stopPropagation();
    this.setState({
      title: messages('finance-setting.key81'/*编辑规则*/),
      ruleInfo: record
    },() => {
      this.setState({showAuditRule: true});
    })
  };

  //进入详情页面
  goDetail = (e,record) => {
    e.stopPropagation();
    let autoAuditDetailRouter = menuRoute.getRouteItem('auto-audit-detail');
    this.context.router.push({pathname:autoAuditDetailRouter.url,state:{ruleInfo:record}});
  };

  //分配公司保存
  handleSelectAddition = (value) => {
    const { selectedDataIds } = this.state;
    let companyArrays = [];
    value.result.map(item => {
      companyArrays.push(item.id);
    });
    let ruleArrays = [];
    selectedDataIds.map(item => {
      ruleArrays.push(Number(item.id));
    });
    let params = {
      ruleIds: ruleArrays,
      companyIds: companyArrays
    };
    autoAuditService.batchAssignCompany(params).then(() => {
      this.setState({showCompanyAssign: false},() => {
        this.getList();
      });
    }).catch(() => {
      message.error(messages('finance-setting.key79'/*出错了，请联系管理员*/));
    });
  };

  handleEdit = () => {
    this.setState({ editing: !this.state.editing });
  };

  handleInfo = () => {
    const { copyInfo } = this.state;
    this.setState({saveLoading: true});
    autoAuditService.updateAutoSetting(copyInfo).then(res => {
      this.setState({
        editInfo: this.getValue(res.data),
        copyInfo: this.getValue(JSON.parse(JSON.stringify(res.data))),
        editing: false,
        saveLoading: false
      })
    }).catch(e => {
      this.setState({saveLoading: false});
      message.error(e.response.data.message);
    });
  };

  render(){
    const { columns, rowSelection, pagination, tableLoading, showAuditRule, title, data, ruleInfo, showCompanyAssign,
      setOfBookId, editing, editInfo, copyInfo, loading, saveLoading } = this.state;
    let checkedValues = [];
    const { tenantMode } = this.props;
    copyInfo.enableAuto && checkedValues.push('enableAuto');
    copyInfo.enableManual && checkedValues.push('enableManual');
    return(
      <div className="auto-audit">
        <div className="auto-audit-title">
          {messages('finance-setting.key100'/*自动审核规则设置*/)}
          {tenantMode && (
            <a onClick={this.handleEdit} style={{marginLeft: '10px'}}>
              {editing ? messages('common.cancel')/*取消*/ : messages('common.edit')/*编辑*/}
            </a>
          )}
        </div>
        <Spin style={{margin: '5px 0px'}} spinning={loading}>
          {messages('finance-setting.key195')/*调用配置：*/}
          {editing ? (
            <div style={{display: 'inline-block', marginLeft: '10px'}}>
              <CheckboxGroup options={[
                {label: messages('finance-setting.key196')/*审批通过后自动调用*/, value: 'enableAuto'},
                {label: messages('finance-setting.key197')/*人工审核时手动调用*/, value: 'enableManual'}]}
                             defaultValue={checkedValues}
                             onChange={checkedValues => {
                               copyInfo.enableAuto = checkedValues.indexOf('enableAuto') > -1;
                               copyInfo.enableManual = checkedValues.indexOf('enableManual') > -1;
                               this.setState({copyInfo});
                             }}/>
            </div>
          ) : (
            <span>
              {editInfo.enableAuto ? messages('finance-setting.key196')/*审批通过后自动调用*/ : '-'}
              &nbsp;&nbsp;
              {editInfo.enableManual ? messages('finance-setting.key197')/*人工审核时手动调用*/ : ''}
            </span>
          )}
        </Spin>
        {
          editing && (
            <div>
              <Button type={'primary'} onClick={() => this.handleInfo()} loading={saveLoading}>{messages('common.save')/*保存*/}</Button>
            </div>
          )
        }
        <div className="auto-audit-desc">{messages('finance-setting.key198')/*说明：*/}</div>
        <div className="auto-audit-desc">{messages('finance-setting.key199')/*1. 是否启用自动审核报销单，若命中规则，则相关的费用标识为免审核，若整张单据/发票袋中的费用均为免审核，则单据/发票袋可自动审核；*/}</div>
        <div className="auto-audit-desc">{messages('finance-setting.key200')/*2. 手动调用即支持在审核界面通过点击自动审核进行规则调用校验；*/}</div>
        <div className="auto-audit-desc">{messages('finance-setting.key201')/*3. 如费用或报销单没有命中规则，则按默认规则执行：正常审核流程；*/}</div>
        <div className="auto-audit-operate">
          <Button type="primary" onClick={this.newAuditRule} disabled={!tenantMode}>{messages('finance-setting.key84'/*新建规则*/)}</Button>
          <Button type="primary" onClick={this.assignCompany} style={{marginLeft:'10px'}} disabled={!tenantMode}>{messages('finance-setting.key94'/*分配公司*/)}</Button>
        </div>
        <div className="auto-audit-total">{messages('finance-setting.key103'/*共*/)}<span>{pagination.total}</span>{messages('finance-setting.key87'/*条数据*/)}</div>
        <ResizeTable
          columns={columns}
          bordered
          rowSelection={rowSelection}
          pagination={pagination}
          loading={tableLoading}
          dataSource={data}
        />
        <SlideFrame show={showAuditRule}
                    title={title}
                    hasFooter={true}
                    hasMask={true}
                    params={{
                      ruleInfo,
                      showAuditRule
                    }}
                    content={AutoAuditRule}
                    onClose={(isRefresh) => {
                      this.setState({showAuditRule: false});
                      isRefresh === true && this.getList();
                    }}
                    afterClose={(isRefresh) => {
                      this.setState({showAuditRule: false});
                      isRefresh === true && this.getList();
                    }}/>
        <ListSelector visible={showCompanyAssign}
                      selectedData={null}
                      type="auto_audit_add_company"
                      extraParams={{setOfBooksId: setOfBookId, roleType: 'TENANT',enabled: true}}
                      onOk={this.handleSelectAddition}
                      onCancel={() => this.setState({ showCompanyAssign: false })}/>
      </div>
    )
  }
}

AutoAudit.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state){
  return {
    tenantInfo: state.login.tenant,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(AutoAudit);
